package com.sys.shiro;

import com.sys.utils.ShiroUtils;
import org.apache.shiro.session.mgt.AbstractValidatingSessionManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Map;

/**
 * @Author com.bhudy
 * @Description 重写DefaultWebSessionManager，解决跨域问题
 * @Date 2019-10-30 23:09:37
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    public CustomSessionManager() {
        super();
        setGlobalSessionTimeout(DEFAULT_GLOBAL_SESSION_TIMEOUT * 48);
    }

    /**
     * 重写getSessionId方法，如果sessionId为null就是没有登陆
     * 优先从cookie中获取access_token
     * 如果没有就从headers请求头中获取access_token
     * 获取到access_token就解密，拿到sessionId
     * 如果没有sessionId就从super.getSessionId(request, response)获取
     *
     * @param request  ServletRequest
     * @param response ServletResponse
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        Map<String, String> cookieMap = ShiroUtils.getToken(httpServletRequest, httpServletResponse);
        Serializable sessionId = null;
        if (cookieMap != null) {
            sessionId = cookieMap.get("sessionId");
        }

        // Serializable sessionId = ShiroUtils.getToken(httpServletRequest, httpServletResponse);

        if (sessionId == null) {
            sessionId = super.getSessionId(request, response);
        }

        return sessionId;
    }
}